package cn.jiyun.security;

import cn.jiyun.pojo.Permission;
import cn.jiyun.pojo.Role;
import cn.jiyun.pojo.User;
import cn.jiyun.serivce.UserService;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

public class SpringSecurityUserService implements UserDetailsService {

    @Reference
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据账号查询用户信息
        User user = userService.findUserByUsername(username);

        if(user==null){
            return null;
        }

        //分配权限
        List<GrantedAuthority> authorities = new ArrayList<>();
        //分配角色
        List<Role> roleList = userService.findRoleByUid(user.getId());
        if(!CollectionUtils.isEmpty(roleList)){
            for (Role role : roleList) {
                authorities.add(new SimpleGrantedAuthority(role.getKeyword()));
                //分配权限
                List<Permission> permissionList = userService.findPermissionByRid(role.getId());
                if(!CollectionUtils.isEmpty(permissionList)){
                    for (Permission permission : permissionList) {
                        authorities.add(new SimpleGrantedAuthority(permission.getKeyword()));
                    }
                }
            }
        }

        return new org.springframework.security.core.userdetails.User(username,user.getPassword(),authorities);
    }
}
